﻿using Mes.原料管理;
using Mes.车间机床.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using static System.Windows.Forms.AxHost;

namespace Mes.车间机床
{
    public partial class WorkshopForm : Form
    {
        private readonly HttpClient _httpClient = new HttpClient();
        private int _currentPage = 1;
        private int _pageSize = 15; // 每页显示10条数据
        private int _totalPages = 1;
        private int _totalRecords;
        public WorkshopForm()
        {
            InitializeComponent();
            InitializeControls();
            MachineInitializeControls();
            skinDataGridView1.CellContentClick += skinDataGridView1_CellContentClick;
            // 添加DataError事件处理，避免错误对话框
            skinDataGridView2.DataError += SkinDataGridView2_DataError;
            skinDataGridView2.CellContentClick += skinDataGridView2_CellContentClick;
            // 添加CellFormatting事件处理，用于显示图片
            skinDataGridView2.CellFormatting += SkinDataGridView2_CellFormatting;
        }

        private void SkinDataGridView2_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略DataError，避免显示错误对话框
            e.ThrowException = false;
        }
        /// <summary>
        /// 分页显示
        /// </summary>
        private void InitializeControls()
        {
            // 设置DataGridView样式
            skinDataGridView1.AutoGenerateColumns = false;
            skinDataGridView1.AllowUserToAddRows = false;
            skinDataGridView1.ReadOnly = true;
            // 检查是否已存在序号列，避免重复添加
            if (skinDataGridView1.Columns["colIndex1"] == null)
            {
                DataGridViewTextBoxColumn indexColumn = new DataGridViewTextBoxColumn
                {
                    Name = "colIndex1",
                    HeaderText = "序号",
                    ReadOnly = true
                };
                skinDataGridView1.Columns.Insert(0, indexColumn); // 插入到第一列
            }
            // 添加列（示例，根据实际需求调整）
            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "id",
                DataPropertyName = "id",
                HeaderText = "ID",
                Visible = false,
            });

            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "workshopCode",
                HeaderText = "车间编号"
            });
            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "workshopName",
                HeaderText = "车间名称"
            });
            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "workshoplocation",
                HeaderText = "车间位置"
            });
            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "workshopHead",
                HeaderText = "车间负责人"
            });
            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "phone",
                HeaderText = "联系方式"
            });
            skinDataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "state",
                HeaderText = "状态"
            });
            //初始化分页信息显示控件
            lblPageInfo.Text = $"当前页: {_currentPage} / 总页数: 0, 总记录数: 0";
            // 初始加载数据
            LoadDataAsync();
        }
        private void UpdatePaginationDisplay()
        {
            lblPageInfo.Text = $"当前页: {_currentPage} / 总页数: {_totalPages}, 总记录数: {_totalRecords}";
        }
        private void btnCha_Click(object sender, EventArgs e)
        {
            _currentPage = 1; // 查询时重置到第一页
            LoadDataAsync();
        }
        // 首页按钮点击事件
        private void btnFrist_Click(object sender, EventArgs e)
        {
            _currentPage = 1;
            LoadDataAsync();
        }
        private void btnShang_Click(object sender, EventArgs e)
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                LoadDataAsync();
            }
        }
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (_currentPage < _totalPages)
            {
                _currentPage++;
                LoadDataAsync();
            }
        }
        // 尾页按钮点击事件
        private void btnLast_Click(object sender, EventArgs e)
        {
            _currentPage = _totalPages;
            LoadDataAsync();
        }
        private void UpdateRowIndices()
        {
            for (int i = 0; i < skinDataGridView1.Rows.Count; i++)
            {
                if (!skinDataGridView1.Rows[i].IsNewRow)
                {
                    skinDataGridView1.Rows[i].Cells["colIndex1"].Value = (i + 1).ToString();
                }
            }
        }
        private async Task LoadDataAsync()
        {
            try
            {
                // 构建查询参数
                var queryParams = new StringBuilder();
                queryParams.Append($"Index={_currentPage}");
                queryParams.Append($"&Size={_pageSize}");

                if (!string.IsNullOrWhiteSpace(textworkshopCode.Text))
                {
                    queryParams.Append($"&WorkshopCode={textworkshopCode.Text.Trim()}");
                }
                if (!string.IsNullOrWhiteSpace(textWorkshopName.Text))
                {
                    queryParams.Append($"&WorkshopName={textWorkshopName.Text.Trim()}");
                }
                if (!string.IsNullOrWhiteSpace(comWorkshopState.Text))
                {
                    queryParams.Append($"&State={comWorkshopState.Text.Trim()}");
                }


                // 调用API
                _httpClient.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                string url = $"http://121.40.174.148:8056/api/WorkShop/GetWorkshop?{queryParams}";
                string jsonResponse = await _httpClient.GetStringAsync(url);

                // 解析响应
                var serializer = new JavaScriptSerializer();
                var apiResponse = serializer.Deserialize<WorkshopRepository>(jsonResponse);

                if (apiResponse?.code == 200 && apiResponse.data?.datas != null)
                {
                    // 更新分页信息
                    _totalRecords = apiResponse.data.totalCount;
                    _totalPages = (int)Math.Ceiling((double)_totalRecords / _pageSize);
                    // 绑定数据到 DataGridView
                    skinDataGridView1.DataSource = apiResponse.data.datas;

                    // 更新分页按钮状态
                    UpdatePaginationButtons();
                    UpdatePaginationDisplay();
                    UpdateRowIndices();
                }
                else
                {
                    MessageBox.Show($"数据加载失败: {apiResponse?.msg ?? "未知错误"}");
                }
                if (!skinDataGridView1.Columns.Contains("btnEdit"))
                {
                    DataGridViewButtonColumn editColumn = new DataGridViewButtonColumn();
                    editColumn.Name = "btnEdit";
                    editColumn.HeaderText = "编辑";
                    editColumn.Text = "编辑";
                    editColumn.UseColumnTextForButtonValue = true;
                    skinDataGridView1.Columns.Add(editColumn);
                }

                // 添加“删除”按钮列
                if (!skinDataGridView1.Columns.Contains("btnDelete"))
                {
                    DataGridViewButtonColumn deleteColumn = new DataGridViewButtonColumn();
                    deleteColumn.Name = "btnDelete";
                    deleteColumn.HeaderText = "删除";
                    deleteColumn.Text = "删除";
                    deleteColumn.UseColumnTextForButtonValue = true;
                    skinDataGridView1.Columns.Add(deleteColumn);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }
        private void UpdatePaginationButtons()
        {

            btnShang.Enabled = (_currentPage > 1);
            btnNext.Enabled = (_currentPage < _totalPages);
            // 更新分页按钮状态（在加载数据后调用）

            btnFrist.Enabled = (_currentPage > 1);
            btnLast.Enabled = (_currentPage < _totalPages);


        }


        private void btnAddWorkshop_Click(object sender, EventArgs e)
        {
            // 创建添加车间的表单实例
            AddWorkshopForm addWorkshopForm = new AddWorkshopForm();

            // 显示添加表单（模态对话框）
            DialogResult result = addWorkshopForm.ShowDialog();

            // 如果用户在添加表单点击了“提交”并成功添加，可以刷新列表
            if (result == DialogResult.OK)
            {
                LoadDataAsync(); // 刷新列表数据
            }
        }

        /// <summary>
        /// 机床分页显示
        /// </summary>
        private void MachineInitializeControls()
        {
            // 设置DataGridView样式
            skinDataGridView2.AutoGenerateColumns = false;
            skinDataGridView2.AllowUserToAddRows = false;
            skinDataGridView2.ReadOnly = true;
            // 检查是否已存在序号列，避免重复添加
            if (skinDataGridView2.Columns["colIndex2"] == null)
            {
                DataGridViewTextBoxColumn indexColumnmatchine = new DataGridViewTextBoxColumn
                {
                    Name = "colIndex2",
                    HeaderText = "序号",
                    ReadOnly = true
                };
                skinDataGridView2.Columns.Insert(0, indexColumnmatchine); // 插入到第一列
            }
            // 添加列（示例，根据实际需求调整）
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                Name = "id",
                DataPropertyName = "id",
                HeaderText = "ID",
                Visible = false,
            });

            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "machineToolCode",
                HeaderText = "设备编号"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "machineToolName",
                HeaderText = "设备名称"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "machineToolType",
                HeaderText = "设备类型"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "machineToolStates",
                HeaderText = "状态"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "productionLines",
                HeaderText = "所有生产线"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "procurementDate",
                HeaderText = "采购日期"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "addPeople",
                HeaderText = "添加人"
            });
            skinDataGridView2.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "addDate",
                HeaderText = "添加日期"
            });
            
            // 添加图片列
            DataGridViewImageColumn imageColumn = new DataGridViewImageColumn
            {
                Name = "img",
                DataPropertyName = "img",
                HeaderText = "设备图片",
                Width = 140,
                ImageLayout = DataGridViewImageCellLayout.Zoom,
                DefaultCellStyle = new DataGridViewCellStyle
                {
                    Alignment = DataGridViewContentAlignment.MiddleCenter
                }
            };
            skinDataGridView2.Columns.Add(imageColumn);
            
            //初始化分页信息显示控件
            lblMachinePageinfo.Text = $"当前页: {_currentPage} / 总页数: 0, 总记录数: 0";
            // 初始加载数据
            MachineLoadDataAsync();
        }

        private void btnShou_Click(object sender, EventArgs e)
        {
            _currentPage = 1;
            MachineLoadDataAsync();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (_currentPage > 1)
            {
                _currentPage--;
                MachineLoadDataAsync();
            }
        }

        private void btnNexts_Click(object sender, EventArgs e)
        {
            if (_currentPage < _totalPages)
            {
                _currentPage++;
                MachineLoadDataAsync();
            }
        }

        private void btnWei_Click(object sender, EventArgs e)
        {
            _currentPage = _totalPages;
            MachineLoadDataAsync();
        }

        private void btnMachineCha_Click(object sender, EventArgs e)
        {
            _currentPage = 1; // 查询时重置到第一页
            MachineLoadDataAsync();
        }
        private async Task MachineLoadDataAsync()
        {
            try
            {
                // 构建查询参数
                var queryParams = new StringBuilder();
                queryParams.Append($"Index={_currentPage}");
                queryParams.Append($"&Size={_pageSize}");

                if (!string.IsNullOrWhiteSpace(textMachineCode.Text))
                {
                    queryParams.Append($"&MachineToolCode={textMachineCode.Text.Trim()}");
                }
                if (!string.IsNullOrWhiteSpace(textMachineName.Text))
                {
                    queryParams.Append($"&MachineToolName={textMachineName.Text.Trim()}");
                }
                if (!string.IsNullOrWhiteSpace(comMachineState.Text))
                {
                    queryParams.Append($"&MachineToolStates={comMachineState.Text.Trim()}");
                }

                // 调用API
                _httpClient.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                string url = $"http://121.40.174.148:8056/api/Machine/GetMachine?{queryParams}";
                string jsonResponse = await _httpClient.GetStringAsync(url);

                // 解析响应
                var serializer = new JavaScriptSerializer();
                var apiResponse = serializer.Deserialize<MachineRepository>(jsonResponse);

                if (apiResponse?.code == 200 && apiResponse.data?.datas != null)
                {
                    // 处理图片数据 - 简化版本
                    foreach (var machine in apiResponse.data.datas)
                    {
                        // 如果图片路径为空，设置为默认值
                        if (string.IsNullOrEmpty(machine.img))
                        {
                            machine.img = "无图片";
                        }
                        // 保持原有的img路径，让DataGridView自己处理图片显示
                    }

                    // 更新分页信息
                    _totalRecords = apiResponse.data.totalCount;
                    _totalPages = (int)Math.Ceiling((double)_totalRecords / _pageSize);
                    // 绑定数据到 DataGridView
                    skinDataGridView2.DataSource = apiResponse.data.datas;

                    // 更新分页按钮状态
                    MachineUpdatePaginationButtons();
                    MachineUpdatePaginationDisplay();
                    MachineUpdateRowIndices();
                }
                else
                {
                    MessageBox.Show($"数据加载失败: {apiResponse?.msg ?? "未知错误"}");
                }
                if (!skinDataGridView2.Columns.Contains("btnEdit"))
                {
                    DataGridViewButtonColumn editColumn = new DataGridViewButtonColumn();
                    editColumn.Name = "btnEdit";
                    editColumn.HeaderText = "编辑";
                    editColumn.Text = "编辑";
                    editColumn.UseColumnTextForButtonValue = true;
                    skinDataGridView2.Columns.Add(editColumn);
                }

                // 添加"删除"按钮列
                if (!skinDataGridView2.Columns.Contains("btnDelete"))
                {
                    DataGridViewButtonColumn deleteColumn = new DataGridViewButtonColumn();
                    deleteColumn.Name = "btnDelete";
                    deleteColumn.HeaderText = "删除";
                    deleteColumn.Text = "删除";
                    deleteColumn.UseColumnTextForButtonValue = true;
                    skinDataGridView2.Columns.Add(deleteColumn);
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }


        private void MachineUpdatePaginationButtons()
        {

            btnPrev.Enabled = (_currentPage > 1);
            btnNexts.Enabled = (_currentPage < _totalPages);
            // 更新分页按钮状态（在加载数据后调用）

            btnShou.Enabled = (_currentPage > 1);
            btnWei.Enabled = (_currentPage < _totalPages);


        }
        private void MachineUpdateRowIndices()
        {
            for (int i = 0; i < skinDataGridView2.Rows.Count; i++)
            {
                if (!skinDataGridView2.Rows[i].IsNewRow)
                {
                    skinDataGridView2.Rows[i].Cells["colIndex2"].Value = (i + 1).ToString();
                }
            }
        }
        private void MachineUpdatePaginationDisplay()
        {
            lblPageInfo.Text = $"当前页: {_currentPage} / 总页数: {_totalPages}, 总记录数: {_totalRecords}";
        }
        /// <summary>
        /// 调用车间删除的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是“删除”按钮列
            if (e.RowIndex >= 0 && e.ColumnIndex == skinDataGridView1.Columns["btnDelete"].Index)
            {
                // 获取当前行的 MaterialId
                string id = skinDataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();

                // 调用删除方法
                await DeleteWorkshop(id);
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == skinDataGridView1.Columns["btnEdit"].Index)
            {
                // 这里可以直接调用 btnEdit_Click 逻辑，或者提取公共代码
                string id = skinDataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();
                UpdateWorkshopForm editForm = new UpdateWorkshopForm(id);
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    await LoadDataAsync();
                }
            }
        }
        private async Task DeleteWorkshop(string id)
        {
            try
            {
                // 1. 确认删除
                if (MessageBox.Show(
                    "确定要删除该车间吗？",
                    "警告",
                    MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }

                // 2. 调用删除接口（参数放在请求体中，而不是URL）
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:7084/");

                    // 构造请求体（如果后端要求）
                    var requestData = new
                    {
                        Id = id
                    };
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    string json = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送 PUT 请求
                    HttpResponseMessage response = await client.PostAsync(
                        "api/WorkShop/DelWorkshop",
                        content);

                    // 3. 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功！");
                        LoadDataAsync(); // 刷新数据
                    }
                    else
                    {
                        string error = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"删除失败：{response.StatusCode}\n{error}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败：{ex.Message}");
            }
        }


        private void btnAddMachine_Click(object sender, EventArgs e)
        {
            int? selectedWorkshopId = null;
            
            // 方法1：从车间列表获取当前选中的车间ID
            if (skinDataGridView1.CurrentRow != null && skinDataGridView1.CurrentRow.DataBoundItem != null)
            {
                var row = skinDataGridView1.CurrentRow;
                // 尝试从当前选中的车间行读取 id
                object idValue = row.Cells["id"]?.Value;
                if (idValue != null && int.TryParse(idValue.ToString(), out int idParsed))
                {
                    selectedWorkshopId = idParsed;
                }
            }
            
            // 方法2：如果车间列表没有选中，提示用户先选择车间
            if (selectedWorkshopId == null)
            {
                MessageBox.Show("请先在车间列表选中一条记录，以便关联机床到该车间。\n\n操作步骤：\n1. 切换到'车间管理'页面\n2. 在车间列表中选中一个车间\n3. 再切换到'机床管理'页面\n4. 点击'添加'按钮", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            AddMachineForm addMachine = new AddMachineForm(selectedWorkshopId);
            DialogResult result= addMachine.ShowDialog();
            if (result== DialogResult.OK)
            {
                MachineLoadDataAsync();
            }
        }

        private void SkinDataGridView2_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 如果是图片列且不是标题行
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && 
                skinDataGridView2.Columns[e.ColumnIndex].Name == "img")
            {
                string imgPath = e.Value?.ToString();
                if (!string.IsNullOrEmpty(imgPath) && imgPath != "无图片")
                {
                    try
                    {
                        // 添加调试信息
                        Console.WriteLine($"尝试加载图片: {imgPath}");
                        
                        // 优先从Images目录加载图片
                        string imagesDirectory = Path.Combine(Application.StartupPath, "Images");
                        string fullImagePath = Path.Combine(imagesDirectory, imgPath);
                        
                        Console.WriteLine($"检查Images目录路径: {fullImagePath}");
                        
                        if (File.Exists(fullImagePath))
                        {
                            Console.WriteLine($"找到图片: {fullImagePath}");
                            // 找到图片文件，显示缩略图
                            using (var originalImage = Image.FromFile(fullImagePath))
                            {
                                var thumbnail = new Bitmap(originalImage, new Size(120, 120));
                                e.Value = thumbnail;
                            }
                        }
                        else
                        {
                            // 如果Images目录中没有找到，尝试其他路径
                            string[] otherPaths = {
                                imgPath, // 原始路径
                                Path.Combine(Application.StartupPath, imgPath), // 应用程序目录
                                Path.Combine(Environment.CurrentDirectory, "Images", imgPath), // 当前目录下的Images
                                Path.Combine(Environment.CurrentDirectory, imgPath) // 当前目录
                            };
                            
                            bool imageFound = false;
                            foreach (string testPath in otherPaths)
                            {
                                Console.WriteLine($"检查其他路径: {testPath}");
                                if (File.Exists(testPath))
                                {
                                    Console.WriteLine($"找到图片: {testPath}");
                                    using (var originalImage = Image.FromFile(testPath))
                                    {
                                        var thumbnail = new Bitmap(originalImage, new Size(120, 120));
                                        e.Value = thumbnail;
                                    }
                                    imageFound = true;
                                    break;
                                }
                            }
                            
                            if (!imageFound)
                            {
                                // 没有找到图片文件，显示文件名
                                string fileName = Path.GetFileName(imgPath);
                                if (string.IsNullOrEmpty(fileName))
                                {
                                    fileName = imgPath;
                                }
                                e.Value = fileName;
                                Console.WriteLine($"未找到图片，显示文件名: {fileName}");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 如果图片加载失败，显示文件名或"加载失败"
                        string fileName = Path.GetFileName(imgPath) ?? "加载失败";
                        e.Value = fileName;
                        Console.WriteLine($"图片加载失败: {ex.Message}, 路径: {imgPath}");
                    }
                }
                else
                {
                    e.Value = "无图片";
                }
            }
        }

        private void btnShua_Click(object sender, EventArgs e)
        {
            MachineLoadDataAsync();
        }

        private void btnWorkshopShua_Click(object sender, EventArgs e)
        {
            LoadDataAsync();
        }


        /// <summary>
        /// 调用机床删除的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinDataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 确保点击的是“删除”按钮列
            if (e.RowIndex >= 0 && e.ColumnIndex == skinDataGridView2.Columns["btnDelete"].Index)
            {
                // 获取当前行的 MaterialId
                string machineId = skinDataGridView2.Rows[e.RowIndex].Cells["id"].Value.ToString();

                // 调用删除方法
                await DeleteMachine(machineId);
            }
            else if (e.RowIndex >= 0 && e.ColumnIndex == skinDataGridView2.Columns["btnEdit"].Index)
            {
                // 这里可以直接调用 btnEdit_Click 逻辑，或者提取公共代码
                string id = skinDataGridView2.Rows[e.RowIndex].Cells["id"].Value.ToString();
                UpdateMachineFrom editForm = new UpdateMachineFrom(id);
                if (editForm.ShowDialog() == DialogResult.OK)
                {
                    await MachineLoadDataAsync(); 
                }
            }
        }
        private async Task DeleteMachine(string machineId)
        {
            try
            {
                // 1. 确认删除
                if (MessageBox.Show(
                    "确定要删除该机床吗？",
                    "警告",
                    MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }

                // 2. 调用删除接口（参数放在请求体中，而不是URL）
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:7084/");

                    // 构造请求体（如果后端要求）
                    var requestData = new
                    {
                        Id = machineId
                    };
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    string json = JsonConvert.SerializeObject(requestData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送 PUT 请求
                    HttpResponseMessage response = await client.PostAsync(
                        "api/Machine/DelMachine",
                        content);

                    // 3. 处理响应
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("删除成功！");
                        MachineLoadDataAsync(); // 刷新数据
                    }
                    else
                    {
                        string error = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"删除失败：{response.StatusCode}\n{error}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败：{ex.Message}");
            }
        }
    }
}
